//
//  AudioPlayer.m
//  Project_ZFR_MUSIC
//
//  Created by 张福润 on 16/2/26.
//  Copyright © 2016年 张福润. All rights reserved.
//

#import "AudioPlayer.h"


@interface AudioPlayer ()
///本地player
@property (nonatomic,strong)AVPlayer *localPalyer;
///
@property (nonatomic,assign,getter=isCurrentPlaying)BOOL currentIsPlaying;

///
@property (nonatomic,strong)NSTimer *timer;
@end


static AudioPlayer *audioPlayer=nil;
@implementation AudioPlayer
//1. 文件是单例
+(instancetype)shareAudioPlayer{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayer=[[AudioPlayer alloc]init];
    });
    return audioPlayer;
}

-(instancetype)init{
    self=[super init];
    if(self){
        //接受avplayer播放完成的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
//结束播放
-(void)playEnd{
    //播放结束
    if(self.delegate&&[self.delegate respondsToSelector:@selector(playFinish)]){
        [self.delegate playFinish];
    }
}


//2. 播放
-(void)playerWithUrl:(NSString *)url{
    //移除监听状态
    [self.localPalyer.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    //创建一个播放器对象
    //1.监听者  2.监听的属性  3.新值旧值  4.附加属性
    AVPlayerItem *item=[[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    //播放
    [self.localPalyer replaceCurrentItemWithPlayerItem:item];
    
}
//
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    if(![keyPath isEqualToString:@"status"]){
        return;
    }
    
    //取出变化的值
    AVPlayerItemStatus value=[change[@"new"] integerValue];
    if(value==AVPlayerItemStatusReadyToPlay){
        //准备好了
        [self play];
    }
    else{
        //准备失败
        //准备情况不知道
    }
}
//3. 暂停/恢复
-(void)playerOrPause{
    if(self.isPlaying){
        //暂停
        [self pause];
    }
    else{
        //播放
        [self play];
        
    }
    
}

-(void)play{
    //
    [self.localPalyer play];
    self.currentIsPlaying=YES;
    
    self.timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

-(void)pause{
    [self.localPalyer pause];
    self.currentIsPlaying=NO;
    //清空timer
    [self.timer invalidate];
    self.timer=nil;
}

-(void)timerAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(playWithTime:)]){
        CGFloat time=self.localPalyer.currentTime.value * 1.0 / self.localPalyer.currentTime.timescale;
        [self.delegate playWithTime:time];
    }
}
//4. 停止
-(void)stop{
    //把时间设置为0
    [self.localPalyer seekToTime:CMTimeMakeWithSeconds(0, self.localPalyer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if(finished){
            //设置完毕
            //暂停播放
            [self pause];
            
        }
        
    }];
   
    
    
}
//5. 从什么时候开始播放
-(void)seekToWithTime:(CGFloat)time{
    //先暂停
//    [self.localPalyer pause];
    [self pause];
    //设置从什么地方开始播放
    [self.localPalyer seekToTime:CMTimeMakeWithSeconds(time, self.localPalyer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if(finished){
            [self play];
        }
    }];
    //播放
    
}

//获取音量
-(CGFloat)volume{
    
    return self.localPalyer.volume;
   
}
-(void)setVolume:(CGFloat)volume{

    self.localPalyer.volume=volume;
}
//设置音量

#pragma mark - 懒加载
-(AVPlayer *)localPalyer{
    if(!_localPalyer){
        _localPalyer=[[AVPlayer alloc]init];
        //初始化音量
        _localPalyer.volume=0.5;
    }
    return _localPalyer;
}
//是否在播放
-(BOOL)isPlaying {
    return self.isCurrentPlaying;
}
@end
